package com.yyq.adms.usermanage.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.yyq.adms.usermanage.bpo.SysDeptsBpo;
import com.yyq.adms.usermanage.bpo.SysUsersBpo;
import com.yyq.adms.usermanage.pojo.SysDepts;
import com.yyq.adms.usermanage.pojo.SysRoles;
import com.yyq.adms.usermanage.pojo.SysUsers;
import com.yyq.adms.usermanage.pojo.SysUsersRoles;
import com.yyq.sos.action.BaseAction;
import com.yyq.sos.constants.ActionType;
import com.yyq.sos.permission.LoginUser;

@Controller("sysUsersRolesAction")
@Scope("prototype")
public class SysUsersRolesAction extends BaseAction
{

	private final static String GO_LIST_ROLES = "goListRoles";
	
	private static final long serialVersionUID = 970236665615134603L;

	SysUsers po = new SysUsers();
	private SysUsersBpo bpo;
	private SysDeptsBpo dBpo;
	
	@Resource(name="sysUsersBpo")
	public void setBpo(SysUsersBpo bpo) {
		bpo.setCls(po.getClass());
		this.bpo = bpo;
	}

	/**
	 * Action操作入口
	 */
	public String execute()throws Exception {
		super.setBpo(bpo);
		super.setObj(po);
		return super.execute();
	}

	public String mainList() {
		LoginUser user = (LoginUser)LoginUser.userThread.get();
		String hql = "select new SysRoles(a.id,a.roleName,a.roleCname,a.sts,a.remark) from "+SysRoles.class.getName()+" a ,"
			     + SysUsersRoles.class.getName()+" b where a.id=b.roleId and b.isGrant='1' and b.userId="+user.getUserId();
		this.setFormValue("roles", bpo.search(hql));
		po = (SysUsers)bpo.findByPk(user.getUserId());
		return super.mainList();
	}

	public String add() {
		return super.add();
	}

	public String goAdd() {
		return super.goAdd();
	}

	public String list() {
		String[] types = (String[])this.getFormValue("type");
		if(types != null){
			if(types[0].equals("DEPTS")){
				dBpo.list(this.getRealPath());
				String[] roleId = (String[])this.getFormValue("roleId");
				String hql = "select new SysUsers(a.id,a.userName,a.userCname) from "+SysUsers.class.getName()+" a,"
							+SysUsersRoles.class.getName()+" b where a.id=b.userId and b.isGrant='0' and b.roleId="
							+roleId[0]+" and b.grantor="+po.getId()+" and b.userId!="+po.getId();
				this.setFormValue("users", bpo.search(hql));
				return "depts";
			}else{
				this.setFormValue("users", bpo.search("from "+SysUsers.class.getName()+" where deptId="+po.getDeptId()));
				return "users";
			}
		}else
			return goListRoles();
	}

	public String update() {
		if(this.getFormValue("type")!=null){
			String[] ids = (String[])this.getFormValue("userIds");
			String[] roleId = (String[])this.getFormValue("roleId");
			LoginUser user = (LoginUser)LoginUser.userThread.get();
			if(ids != null && ids.length > 0){
				String hql = "select new SysUsers(a.id,a.userName,a.userCname) from "+SysUsers.class.getName()+" a,"+SysUsersRoles.class.getName()
							+" b where a.id=b.userId and b.roleId="+roleId[0]+" and b.grantor<>"+user.getUserId()
							+" and (";
				for(int i = 0, count = ids.length; i < count; ++i){
					if(i!=0)
						hql += " or ";
					hql += " b.userId="+ids[i];
				}
				hql += ")";
				List users = bpo.search(hql);
				if(users.size()>0){
					StringBuffer buf = new StringBuffer("{processId:\"-1\",msg:\"无法完成授权，下列用户已经具有该角色:");
					for(int i = 0, count = users.size(); i < count; ++i){
						if(i != 0)
							buf.append(",");
						SysUsers o = (SysUsers)users.get(i);
						buf.append(o.getUserName()).append("(").append(o.getUserCname()).append(")");
					}
					buf.append("\"}");
					this.setMsg(buf.toString());
				}else if(bpo.delete("delete "+SysUsersRoles.class.getName()+" where roleId="+roleId[0]+" and grantor="+user.getUserId())){
					List list = new ArrayList();
					for(int i = 0, count = ids.length; i < count; ++i){
						SysUsersRoles vo = new SysUsersRoles();
						vo.setGrantDate(new Date());
						vo.setGrantor(user.getUserId());
						vo.setIsGrant("0");
						vo.setRoleId(new Long(roleId[0]));
						vo.setUserId(new Long(ids[i]));
						list.add(vo);
					}
					if(bpo.save(list.toArray(new SysUsersRoles[0]))!=null)
						this.setMsg("{processId:\"1\",msg:\"授权成功\"}");
					else
						this.setMsg("{processId:\"-1\",msg:\"授权失败\"}");
				}else
					this.setMsg("{processId:\"-1\",msg:\"授权失败\"}");
			}else
				this.setMsg("{processId:\"1\",msg:\"授权成功\"}");
			return ActionType.ACTION_MSG;
		}
		return updateRoles();
	}
	
	private String goListRoles() {
		po = (SysUsers) bpo.findByPk(po.getId());
		this.setFormValue("userRoles",  bpo.getUserRoles(po));
		return GO_LIST_ROLES;
	}
	
	private String updateRoles() {
		boolean success = bpo.updateUserRoles(po, (String[]) getFormValue("roleIds"),(String[]) getFormValue("grantIds"));
		if(success) {
			this.setMsg("{processId:\"1\",msg:\"更新成功\"}");
		} else {
			this.setMsg("{processId:\"1\",msg:\"更新失败\"}");
		}
		return ActionType.ACTION_MSG;
	}
	
	public SysUsers getPo() {
		return po;
	}

	public void setPo(SysUsers po) {
		this.po = po;
	}

	@Resource
	public void setDBpo(SysDeptsBpo bpo) {
		dBpo = bpo;
	}
}
